package org.moflon.moca;

import java.io.File;
import java.io.FilenameFilter;
import java.util.List;

import org.apache.log4j.BasicConfigurator;
import org.moflon.moca.html.unparser.HtmlUnparserAdapter;
import org.moflon.moca.txt.unparser.TxtUnparserAdapter;
import org.moflon.util.eMoflonEMFUtil;

import BoardGame.Board;
import BoardGame.BoardGameFactory;
import BoardGame.BoardGamePackage;
import Moca.CodeAdapter;
import Moca.MocaFactory;
import Moca.MocaPackage;
import MocaTree.MocaTreePackage;
import ModelToTree.ModelToTreeFactory;
import ModelToTree.ModelToTreeTransformer;
import Rules.RulesPackage;

public class MocaMain {

	private static CodeAdapter codeAdapter;

	public static void main(String[] args) {
		BasicConfigurator.configure();

		// Register parsers and unparsers
		codeAdapter = MocaFactory.eINSTANCE.createCodeAdapter();
		BoardGamePackage.eINSTANCE.eClass();
		RulesPackage.eINSTANCE.eClass();
		// EPackage.Registry.INSTANCE.put(BoardGamePackage.eNS_URI,
		// BoardGamePackage.eINSTANCE);

		// transform Board to tree
		Board board = (Board) eMoflonEMFUtil
				.loadModel(BoardGamePackage.eINSTANCE,
						"instances/in/chessboard.xmi", null);

		final ModelToTreeTransformer modelToTreeTransformer = ModelToTreeFactory.eINSTANCE
				.createModelToTreeTransformer();
		MocaTree.File mocaFile = modelToTreeTransformer.transformBoard(board);

		eMoflonEMFUtil.saveModel(MocaPackage.eINSTANCE, mocaFile,
				"instances/tree.board.xmi");

		final File txtOutDir = new File("instances/out/txt");
		final File htmlOutDir = new File("instances/out/html");

		// Perform tree-to-text
		// TXT unparser
		codeAdapter.getUnparser().clear();
		codeAdapter.getUnparser().add(new TxtUnparserAdapter());
		codeAdapter.unparseFile(mocaFile, txtOutDir);

		// HTML unparser
		codeAdapter.getUnparser().clear();
		codeAdapter.getUnparser().add(new HtmlUnparserAdapter());
		codeAdapter.unparseFile(mocaFile, htmlOutDir);

		// rename files in order to be able to comfortably open them
		final File[] filesToBeRenamedAsTxt = txtOutDir
				.listFiles(new FilenameFilter() {

					@Override
					public boolean accept(File file, String name) {
						return !name.equals(".svn") && !name.endsWith(".txt");
					}
				});
		final File[] filesToBeRenamedAsHtml = htmlOutDir
				.listFiles(new FilenameFilter() {

					@Override
					public boolean accept(File file, String name) {
						return !name.equals(".svn") && !name.endsWith(".html");
					}
				});
		
		for (final File file : filesToBeRenamedAsTxt){
			file.renameTo(new File(file.getAbsoluteFile() + ".txt"));
		}
		for (final File file : filesToBeRenamedAsHtml)
		{
			file.renameTo(new File(file.getAbsoluteFile() + ".html"));
		}
		
		// save here as the tree is sorted just before unparsing
		eMoflonEMFUtil.saveModel(MocaPackage.eINSTANCE, mocaFile,
				"instances/tree.board.xmi");

	}
}